use std::{
    fs::{self, File},
    io::Write,
    path::Path,
};

use my_rust_core::shared::{app_config_service, util::generate_random_u32};

pub fn save_upload(filename: &str, data: &[u8]) {
    let upload_config = &app_config_service::APP_CONFIG.resource.upload;
    let upload_root_path = Path::new(&upload_config.root_file_path);

    if !upload_root_path.exists() {
        fs::create_dir_all(upload_root_path).unwrap();
    }

    let target_filename_path = upload_root_path.join(format!(
        "{}-{}",
        generate_random_u32(10000, 99999),
        filename
    ));

    let target_filename = target_filename_path.clone();

    let mut file = File::create(target_filename_path).unwrap();
    file.write_all(&data).unwrap();

    println!("{} saved to {:?}", filename, target_filename);
}
